<template>
  <div class="course-detail">
    <Header/>


    <!-- 课程主体内容 -->
    <div class="course-container" v-if="courseData">
      <!-- 课程基本信息 -->
      <div class="course-info">
        <div class="course-image">
          <img :src="courseData.course_img" :alt="courseData.name">
        </div>
        <div class="course-summary">
          <h1 class="title">{{ courseData.name }}</h1>
          <div class="stats">
            <span class="stat-item"><i class="fas fa-user"></i>{{ courseData.students }}人在学</span>
            <span class="stat-item"><i class="fas fa-list"></i>{{ courseData.lessons }}课时</span>
            <span class="stat-item"><i class="fas fa-clock"></i>{{ courseData.pub_lessons }}已更新</span>
          </div>
          <div class="price-info" v-if="courseData.course_type=='2'">
            <span class="current-price">¥{{ courseData.price }}</span>
            <span class="original-price">¥{{ courseData.original_price }}</span>
          </div>
          <button class="buy-btn" v-if="courseData.course_type=='2'" @click="addToCart(courseData.id)">加入购物车
          </button>
          <button class="buy-btn" v-else>免费课程,直接观看</button>
        </div>
      </div>

      <!-- 讲师信息 -->
      <div class="teacher-info">
        <div class="avatar">
          <img :src="courseData.teacher.avatar" :alt="courseData.teacher.name">
        </div>
        <div class="teacher-detail">
          <h3 class="name">{{ courseData.teacher.name }}</h3>
          <p class="title">{{ courseData.teacher.title }}</p>
          <p class="description">{{ courseData.teacher.brief }}</p>
        </div>
      </div>

      <!-- 课程大纲 -->
      <div class="course-outline">
        <h2 class="section-title">课程大纲</h2>
        <div class="outline-content">
          <!-- 第一章 -->
          <div class="chapter" v-for="chapter in courseData.chapters" :key="chapter.id">
            <div class="chapter-header">
              <h3>第{{ chapter.number }}章 {{ chapter.title }}</h3>
              <span class="duration">共{{ chapter.lessons.length }}课时</span>
            </div>
            <div class="lessons">
              <div class="lesson" v-for="lesson in chapter.lessons" :key="lesson.id">
                <span class="lesson-title" v-if="lesson.is_free_trail"><a
                    :href="lesson.link">{{ lesson.orders }} : {{ lesson.title }}</a></span>
                <span class="lesson-title" v-else>{{ lesson.orders }} : {{ lesson.title }}</span>
                <span class="lesson-duration">{{ lesson.duration }}</span>
                <span class="free-tag" v-if="lesson.is_free_trail">免费</span>
              </div>

            </div>
          </div>

          <!-- 第二章 -->

        </div>
      </div>

      <!-- 课程介绍 -->
      <div class="course-introduction">
        <h2 class="section-title">课程介绍</h2>
        <div class="introduction-content" v-html="courseData.description">

        </div>
      </div>

      <!-- 课程收获 -->
      <div class="course-gains">
        <h2 class="section-title">课程收获</h2>
        <div class="gains-content" v-html="courseData.outcomes">

        </div>
      </div>

      <!-- 适合人群 -->
      <div class="suitable-for">
        <h2 class="section-title">适合人群</h2>
        <div class="suitable-content" v-html="courseData.audience"></div>


      </div>
    </div>
  </div>
</template>

<script setup>
import Header from '../components/Header.vue'
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";


const route = useRoute()
const router = useRouter()
const courseId = route.params.id
const courseData = ref(null)


const refreshToken = async () => {
  const refresh_token = localStorage.getItem("refresh_token") || sessionStorage.getItem("refresh_token")
  if (!refresh_token) {
    ElMessage.warning("no refresh_token")
    return
  }

  try {
    const res = await axios.post('http://localhost:8000/jwt/refresh/', {
      "refresh": refresh_token
    })

    console.log("res", res)

    if (res.data.access) {
      const newToken = res.data.access
      localStorage.setItem("token", newToken)
      sessionStorage.setItem("token", newToken)
      return newToken
    }
  } catch (error) {
    console.log(error)
    return ""
  }


}

const addToCart = async (courseId) => {

  const token = localStorage.getItem("token") || sessionStorage.getItem("token")

  if (!token) {
    ElMessage.warning("请先登录")
    router.push("/login")
    return
  }

  try {
    const res = await axios.post("http://localhost:8000/cart/add/", {
      "course_id": courseId,
      "quantity": 1
    }, {
      headers: {
        "Authorization": "Bearer " + token
      }
    })

    //判断http状态码

    if (res.data.code == 1) {
      ElMessage.success("添加成功")
    } else {
      ElMessage.error(res.data.message || "添加失败")
    }


  } catch (error) {
    console.log(error)

    if (error.response.status == 401) {
      //ElMessage.warning("登录已过期")
      const newToken = await refreshToken()

      console.log("newToken", newToken)

      if (newToken) {
        console.log("newToken1111", newToken)
        const tryRes = await axios.post("http://localhost:8000/cart/add/", {
          "course_id": courseId,
          "quantity": 1
        }, {
          headers: {
            "Authorization": "Bearer " + newToken
          }
        })

        console.log("tryRes", tryRes)

        if (tryRes.data.code == 1) {
          ElMessage.success("添加成功")
        } else {
          ElMessage.error(tryRes.data.message || "添加失败")
        }

      }

    }
    ElMessage.error("error添加失败")
  }


}


// const  addToCart = (course_id)=>{
//   const token = localStorage.getItem('token')||sessionStorage.getItem('token')
//   axios.post("http://127.0.0.1:8000/cart/add/",{course_id:course_id}, {
//     headers:{
//       "Authorization":'Bearer '+token
//     }
//   }).then(res=>{
//     console.log(res)
//     if(res.data.code==1){
//       ElMessage.info("添加成功")
//       router.push("/cart")
//     }
//   })
//
// }


const fetchCourse = async () => {

  const res = await axios.get('http://127.0.0.1:8000/courses/' + courseId)
  if (res.data.code == 1) {
    console.log(res.data.data)
    courseData.value = res.data.data
  }

}

onMounted(() => {
  fetchCourse()

})

</script>

<style scoped>
.course-detail {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.course-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 课程基本信息样式 */
.course-info {
  display: flex;
  gap: 30px;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.course-image {
  flex: 0 0 400px;
}

.course-image img {
  width: 100%;
  border-radius: 8px;
}

.course-summary {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.title {
  font-size: 24px;
  color: #333;
  margin: 0 0 20px;
}

.stats {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  color: #666;
  font-size: 14px;
}

.stat-item i {
  margin-right: 5px;
}

.price-info {
  margin-bottom: 20px;
}

.current-price {
  font-size: 28px;
  color: #ff5858;
  font-weight: bold;
  margin-right: 10px;
}

.original-price {
  color: #999;
  text-decoration: line-through;
  font-size: 16px;
}

.buy-btn {
  width: 180px;
  height: 48px;
  background: #ff5858;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.buy-btn:hover {
  background: #ff4040;
}

/* 讲师信息样式 */
.teacher-info {
  display: flex;
  gap: 20px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.teacher-detail {
  flex: 1;
}

.teacher-detail .name {
  font-size: 18px;
  color: #333;
  margin: 0 0 5px;
}

.teacher-detail .title {
  color: #666;
  font-size: 14px;
  margin: 0 0 10px;
}

.teacher-detail .description {
  color: #999;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
}

/* 课程大纲样式 */
.course-outline,
.course-introduction,
.course-gains,
.suitable-for {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.section-title {
  font-size: 18px;
  color: #333;
  margin: 0 0 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.chapter {
  margin-bottom: 20px;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.chapter-header h3 {
  font-size: 16px;
  color: #333;
  margin: 0;
}

.duration {
  color: #999;
  font-size: 14px;
}

.lessons {
  padding-left: 20px;
}

.lesson {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  color: #666;
  font-size: 14px;
}

.lesson-left {
  flex: 1;
  margin-right: 15px;
  display: flex;
  justify-content: flex-start;
}

.lesson-left > div {
  width: 100%;
  text-align: left;
}

.lesson-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.lesson-title {
  display: inline-block;
  text-align: left;
  color: #666;
  font-size: 14px;
  cursor: default;
}

a.lesson-title {
  color: #333;
  text-decoration: none;
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #ff5858;
  }
}

.lesson-duration {
  color: #999;
  white-space: nowrap;
}

.free-tag {
  color: #52c41a;
  font-size: 12px;
  padding: 2px 6px;
  border: 1px solid #52c41a;
  border-radius: 4px;
  white-space: nowrap;
}

/* 其他内容区域样式 */
.introduction-content,
.gains-content,
.suitable-content {
  color: #666;
  font-size: 14px;
  line-height: 1.8;
}

/* 加载状态样式 */
.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  font-size: 16px;
  color: #666;
}

/* 课程卡片鼠标样式 */
.course-card {
  cursor: pointer;
  transition: all 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

:deep(.introduction-content),
:deep(.gains-content),
:deep(.suitable-content) {
  ul {
    list-style: disc;
    padding-left: 20px;
    margin: 10px 0;
  }

  li {
    margin-bottom: 8px;
  }
}
</style>